import asyncio
from uuid import uuid4

from common.task_manager import TaskManager

from common.types import (
    AgentCard, AgentCapabilities, AgentSkill, AgentProvider, IframeData, IframeSecurity,
    Task, TaskStatus, TaskState, Message, TextPart, DataPart, FilePart, Artifact,
    TaskSendParams, TaskQueryParams, TaskNotFoundError, TaskStatusUpdateEvent, TaskArtifactUpdateEvent
)

class MessageUtil:
    __instance = None

    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super().__new__(cls)
        return cls.__instance

    def __init__(self):
        pass

    @classmethod
    def get_instance(cls):
        if not cls.__instance:
            cls()
        return cls.__instance

    async def send_text_event(self, task_manager: TaskManager, task: Task, text: str, metadata: dict = None, state: TaskState = TaskState.WORKING, final: bool = False):
        """推送同步处理工件事件"""
        await task_manager.emit_status_event(task, state, text, metadata=metadata, final=final)
        await asyncio.sleep(0.001)# 极短暂的延迟确保事件被处理


    async def send_artifact_mermaid_event(self, task_manager: TaskManager, task: Task, artifact_name: str, artifact_description: str, artifact_value: str, metadata: dict = None, artifact_end: bool = False):
        """推送流程图工件事件"""
        if metadata is None:
            metadata = {}
        metadata['dataType'] = 'artifact'
        metadata['artifactType'] = 'mermaid'

        # 工件数据
        event_message = {'type': 'artifact', 'name': artifact_name, 'description': artifact_description,
                         'text': artifact_value, 'artifactType': 'mermaid', 'append': not artifact_end, 'lastChunk': artifact_end}
        await task_manager.emit_status_event(task, TaskState.WORKING, event_message, metadata=metadata, final=False)
        await asyncio.sleep(0.001)


    async def send_image_event(self, task_manager: TaskManager, task: Task, file_name: str, base64_value: str,mime_type: str, metadata: dict = None, state: TaskState = TaskState.WORKING, final: bool = False):
        """推送处理图片事件"""
        # 图片数据
        file_bytes = {'type': 'fileWithBytes', 'mimeType': mime_type, 'name': file_name, 'bytes': base64_value}
        event_message = {"file": file_bytes}
        await task_manager.emit_status_event(task, state, event_message, metadata=metadata, final=final)
        await asyncio.sleep(0.001)# 极短暂的延迟确保事件被处理


    async def send_file_event(self, task_manager: TaskManager, task: Task, file_name: str, file_uri: str,mime_type: str, metadata: dict = None, state: TaskState = TaskState.WORKING, final: bool = False):
        """推送处理文件事件"""
        # 文件数据
        file_response = {'type': 'fileWithUri', 'mimeType': mime_type, 'name': file_name, 'uri': file_uri}
        event_message = {"file": file_response}
        await task_manager.emit_status_event(task, state, event_message, metadata=metadata, final=final)
        await asyncio.sleep(0.001)# 极短暂的延迟确保事件被处理


    async def send_iframe_event(self, task_manager: TaskManager, task: Task, src: str, title: str, iframe_metadata: dict, iframe_extra_values: dict = None, metadata: dict = None, state: TaskState = TaskState.WORKING, final: bool = False):
        """推送处理iframe事件"""
        # iframe数据
        if metadata is None:
            metadata = {}
        metadata["dataType"] = "iframe"

        iframe = {"iframeId": str(uuid4()),
                  "title": title,
                  "src":src,
                  "width":"100%",
                  "height":600,
                  "allowFullscreen":True,
                  "interactionMode":"interactive",
                  "security": None,
                  # "security" = {
                  #     "allowedOrigins":["https://www.mastercom.cn/index"],
                  #     "requireAuth":False
                  # },
                  "metadata": iframe_metadata
        }
        if iframe_extra_values:
            # 只更新iframe中已有的键
            filtered_extra_values = {k: v for k, v in iframe_extra_values.items() if k in iframe}
            iframe.update(filtered_extra_values)

        event_message = {"data": {"iframe": iframe}}
        await task_manager.emit_status_event(task, state, event_message, metadata=metadata, final=final)
        await asyncio.sleep(0.001)  # 极短暂的延迟确保事件被处理


messageUtil = MessageUtil.get_instance()